package main

import (
	"fmt"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	_ "github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
)

// 定义一个全局翻译器T
var Trans ut.Translator

var (
	validate *validator.Validate
)

func main() {
	zhT := zh.New() // 中文翻译器
	enT := en.New() // 英文翻译器
	uni := ut.New(enT, zhT, enT)
	var _ bool
	Trans, _ = uni.GetTranslator("zh")
	validate = validator.New()
	_ = zhTranslations.RegisterDefaultTranslations(validate, Trans)
	translateAll(Trans)
	translateIndividual(Trans)
	translateOverride(Trans)
}

//  翻译校验所有字段
func translateAll(trans ut.Translator) {
	type User struct {
		Username string `validate:"required"`
		Tagline  string `validate:"required,lt=10"`
		Tagline2 string `validate:"required,gt=1"`
	}

	user := User{
		Username: "Joeybloggs",
		Tagline:  "This tagline is way too long.",
		Tagline2: "1",
	}

	err := validate.Struct(user)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		fmt.Println(errs.Translate(trans))
	}
}

//  翻译校验特定的字段
func translateIndividual(trans ut.Translator) {
	type User struct {
		Username string `validate:"required"`
	}
	var user User
	err := validate.Struct(user)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		for _, e := range errs {
			// can translate each error one at a time.
			fmt.Println(e.Translate(trans))
		}
	}
}

//  翻译覆盖原来的信息
func translateOverride(trans ut.Translator) {
	_ = validate.RegisterTranslation("required", trans, func(ut ut.Translator) error {
		// 可以通过这里修改原来的描述信息
		return ut.Add("required", "{0} 不能为空!", true)
	}, func(ut ut.Translator, fe validator.FieldError) string {
		t, _ := ut.T("required", fe.Field())
		return t
	})
	type User struct {
		Username string `validate:"required"`
	}
	var user User
	err := validate.Struct(user)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		for _, e := range errs {
			fmt.Println(e.Translate(trans))
		}
	}
}
